package com.service.note;

import com.dto.NoteDto;
import com.mapper.generator.ShNoteMapper;
import com.mapper.self.NoteMapper;
import com.pojo.ShNote;
import com.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by Huoyunren on 2016/5/18.
 */
@Service
public class NoteServiceImpl implements NoteService {
    @Autowired
    private ShNoteMapper shNoteMapper;
    @Autowired
    private NoteMapper noteMapper;

    @Override
    public NoteDto add(String uuid, String content) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        ShNote note = new ShNote();
        note.setContent(content);
        note.setUuid(uuid);
        note.setEmail(request.getSession().getAttribute("email").toString());
        note.setCreateTime(DateUtils.currentDate());
        shNoteMapper.insertSelective(note);
        NoteDto noteDto = queryByNoteId(note.getId());
        noteDto.setCreateTime(noteDto.getCreateTime().substring(0, noteDto.getCreateTime().length() - 2));
        return noteDto;
    }

    @Override
    public NoteDto queryByNoteId(Integer noteId) {
        return noteMapper.queryByNoteId(noteId);
    }

    @Override
    public List<NoteDto> list(String uuid, Integer pageNo, Integer pageSize) {
        if (pageNo == null) {
            pageNo = 0;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        if (pageNo > 0) {
            pageNo -= 1;
        }
        List<NoteDto> list = noteMapper.list(uuid, pageNo * pageSize, pageSize);
        for (NoteDto noteDto : list) {
            noteDto.setCreateTime(noteDto.getCreateTime().substring(0, noteDto.getCreateTime().length() - 2));
        }
        return list;
    }
}
